<?php

use Core\AdminController;
use Models\Damage;
use Models\Product;
use Models\Item;
use Models\PurchaseRecord;

class DamageController extends AdminController
{
	public function index()
	{
		$type = $this->input->get('type');
		$start_date = $this->input->get('start_date');
		$end_date = $this->input->get('end_date');
		$code = $this->input->get('code');

		$damage = new Damage;
		if($code){
			$item = (new Item)->where('barcode',$code)->get_one();
			if($item){
				$damage->where('item_id',$item['id']);
			}
		}
		if($type === '0' || $type == 1){
			$damage->where('type',$type);
		}
		if($start_date){
			$damage->where('create_time >=',$start_date);
		}
		if($end_date){
			$damage->where('create_time <=',$end_date);
		}


		$page = $damage->order_by('id desc')
			->with(['product', 'item','cashier'])
			->paginate(20);
		//$this->output->enable_profiler(TRUE);
		return $this->load->view('admin/damage/index', [
			'page' => $page,
		]);
	}

	public function create()
	{
		if(IS_AJAX){
			$this->db->trans_start();
			$code = $this->input->post('code');
			$item = (new Item)->where('barcode',$code)->get_one();
			if(!$item){
				echo json_encode(['code'=>1,'msg'=>'条形码输入错误']);
				return;
			}
			if($item['stock'] < abs($this->input->post('qty'))){
				echo json_encode(['code'=>1,'msg'=>'库存不足，总库存只有'.$item['stock']]);
				return;
			}
			$damage = new Damage();
			$damage['create_time'] = date('Y-m-d H:i:s');
			$damage['type'] = $this->input->post('type');
			$damage['product_id'] = $item['product_id'];
			$damage['item_id'] = $item['id'];
			$damage['cashier_id'] = 0;
			$damage['qty'] = abs($this->input->post('qty'));
			$damage->add();

			//减商品库存
			$item['stock'] -= $this->input->post('qty');
			$item->update();
			
			$product = (new Product)->find($item['product_id']);
			$product['stock'] -= $this->input->post('qty');
			$product->update();
			
			(new PurchaseRecord)->stock($item['id'],-$this->input->post('qty'));


			$this->db->trans_complete();
			echo json_encode(['code'=>0,'msg'=>'success']);
		}else{
			return $this->load->view('admin/damage/create');
		}
		
	}
}